package com.xinqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinqi.bean.Goods;
import com.xinqi.bean.GoodsOrder;
import com.xinqi.common.R;
import com.xinqi.mapper.GoodsOrderMapper;
import com.xinqi.service.GoodsOrderService;
import com.xinqi.service.IGoodsService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author xin麒
 * @date 2023/2/21 11:03
 */
@Service
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderMapper, GoodsOrder> implements GoodsOrderService {
    @Autowired
    private IGoodsService goodsService;

    @Override
    public R buyOneGoods(Long goodsId, Long userId) {
        //其他业务

        //一人一单业务实现过程：
        synchronized (userId.toString().intern()) {
            GoodsOrderService proxy = (GoodsOrderService)AopContext.currentProxy();

            return proxy.createGoodsOrder(goodsId, userId);
        }

    }

    @Transactional
    public R<String> createGoodsOrder(Long goodsId, Long userId) {
        QueryWrapper<GoodsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goodsId)
                .eq("user_id", userId);
        GoodsOrder goodsOrder = getOne(queryWrapper);
        if (goodsOrder != null) return R.fail("can not get the goods");

        Goods goods = goodsService.getById(goodsId);

        if (goods == null || goods.getStock() <= 0) return R.fail("has not any stock");//step 1

        boolean success = goodsService.update()
                .setSql("stock = stock - 1")
                .eq("id", goodsId)
                .gt("stock", goods.getStock() / 3)//这里比较前后的数据是否相等，相等就可以修改库存
                .update();//step 2

        if (!success) {
            return R.fail("has not any stock");
        }
        goodsOrder = new GoodsOrder();
        goodsOrder.setGoodsId(goodsId);
        goodsOrder.setUserId(userId);
        save(goodsOrder);
        return R.success("buy one success");
    }
}